<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="车间" prop="fab" label-width="40px">
          <el-select v-model="queryParams.fab" placeholder="请选择车间" @change="getFactoryAreaIdList(queryParams.fab)" clearable style="width: 150px;">
            <el-option v-for="dict in factoryIdOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="制造区域" prop="factoryAreaId">
          <el-select v-model="queryParams.area" placeholder="请选择制造区域" @change="getProductionTypeIdList(queryParams.area)" clearable style="width: 150px;">
            <el-option v-for="dict in factoryAreaIdOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="制造类型" prop="productionTypeId">
          <el-select v-model="queryParams.process" placeholder="请选择制造类型" @change="getEqpList(queryParams.process)" clearable style="width: 150px;">
            <el-option v-for="dict in listProductionTypeOptions" :key="dict.value" :label="dict.label"
              :value="dict.value" />
          </el-select>
        </el-form-item>
      <el-form-item label="设备id" prop="eqpId">
        <el-input v-model="queryParams.eqpId" placeholder="请输入设备id" clearable style="width: 150px;" @keyup.enter="handleQuery" />
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['funConfig:module:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['funConfig:module:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['funConfig:module:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['funConfig:module:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList">
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </right-toolbar>
    </el-row>

    <t-ag-grid
          :style="{height: height}"
          :column-defs="column"
          :row-data="moduleList"
          :row-buffer="20"
          row-selection="multiple"
          :suppress-row-click-selection="true"
          :row-multi-select-with-click="true"
          align="center"
          header-align="center"
          :defaultColDef = "{
              menuTabs: ['filterMenuTab', 'columnsMenuTab']
          }"
          @selection-changed="selectionChanged"
          />

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改产量统计对话框 -->
    <el-dialog :title="title" v-model="open" width="350px" append-to-body>
      <el-form ref="moduleRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="车间" prop="fab">
          <el-select v-model="form.fab" placeholder="请选择车间" :disabled="isEdit == 'Y'" @change="getFactoryAreaIdList(form.fab)" clearable style="width: 180px;">
            <el-option v-for="dict in factoryIdOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="制造区域" prop="factoryAreaId">
          <el-select v-model="form.area" placeholder="请选择制造区域" :disabled="isEdit == 'Y'" @change="getProductionTypeIdList(form.area)" clearable style="width: 180px;">
            <el-option v-for="dict in factoryAreaIdOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="制造类型" prop="productionTypeId">
          <el-select v-model="form.process" placeholder="请选择制造类型" :disabled="isEdit == 'Y'" @change="getEqpList(form.process)" clearable
            style="width: 180px;">
            <el-option v-for="dict in listProductionTypeOptions" :key="dict.value" :label="dict.label"
              :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备ID" prop="eqpId" v-if="isEdit == 'N'">
          <el-select v-model="form.eqpId" placeholder="请选择设备ID" clearable style="width: 180px;">
            <el-option v-for="dict in eqpIdList" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="设备ID" prop="eqpId" v-if="isEdit == 'Y'">
          <el-input v-model="form.eqpId" placeholder="请输入设备ID" :disabled="isEdit == 'Y'" style="width: 180px;" />
        </el-form-item>
        <el-form-item label="源设备id" prop="moveId">
          <el-input v-model="form.moveId" placeholder="请输入源设备id" style="width: 180px;"/>
        </el-form-item>
        <el-form-item label="部门名称" prop="dept">
          <el-input v-model="form.dept" placeholder="请输入部门名称" style="width: 180px;"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Module">
  import { listModule, getModule, delModule, addModule, updateModule } from "@/api/funConfig/module"
  // options
  // import { factoryIdOptions, factoryAreaIdOptions, listProductionTypeOptions, listMachineTypeOptions } from './options'
  import useUserStore from '@/store/modules/user'
  import request from '@/utils/request'
  const { proxy } = getCurrentInstance()

  const moduleList = ref([])
  const open = ref(false)
  const loading = ref(true)
  const showSearch = ref(true)
  const ids = ref([])
  const single = ref(true)
  const multiple = ref(true)
  const total = ref(0)
  const title = ref("")
  const isEdit = ref("")

  const data = reactive({
    form: {},
    queryParams: {
      pageNum: 1,
      pageSize: 10000,
      fab: null,
      area: null,
      process: null,
      dept: null,
      mainStep: null,
      topEqp: null,
      bySiteFlag: null,
      eqpId: null,
      createUser: useUserStore().name,
      updateUser: useUserStore().name
    },
    rules: {
      fab: [
        { required: true, message: "车间不能为空", trigger: "blur" }
      ],
      eqpId: [
        { required: true, message: "制造类型不能为空", trigger: "blur" }
      ]
    }
  })
  const eqpIdList = ref([])
  const factoryIdOptions = ref([])
  const factoryAreaIdOptions = ref([])
  const listProductionTypeOptions = ref([])
  const getEqpListInfo = (process) => {
    return request({
      url: '/funConfig/module/getEqpIdList/?process=' + process,
      method: 'get'
    })
  }
  const getEqpList = (process) => {
    eqpIdList.value = []
    getEqpListInfo(process).then((res) => {
      res.rows.forEach(item => {
        eqpIdList.value.push({
          label: item,
          value: item
        })
      })
    })
  }

  const getFactoryIdListInfo = () => {
    return request({
      url: '/parameter/getFactoryIdList/',
      method: 'get'
    })
  }
  const getFactoryIdList = () => {
    factoryIdOptions.value = []
    getFactoryIdListInfo().then((res) => {
      res.rows.forEach(item => {
        factoryIdOptions.value.push({
          label: item,
          value: item
        })
      })
    })
  }
  getFactoryIdList()
  const getFactoryAreaIdListInfo = (factoryId) => {
    return request({
      url: '/parameter/getFactoryAreaIdList/?factoryId=' + factoryId,
      method: 'get'
    })
  }
  const getFactoryAreaIdList = (factoryId) => {
    factoryAreaIdOptions.value = []
    getFactoryAreaIdListInfo(factoryId).then((res) => {
      res.rows.forEach(item => {
        factoryAreaIdOptions.value.push({
          label: item,
          value: item
        })
      })
    })
  }
  const getProductionTypeIdListInfo = (factoryAreaId) => {
    return request({
      url: '/parameter/getProductionTypeIdList/?factoryAreaId=' + factoryAreaId,
      method: 'get'
    })
  }
  const getProductionTypeIdList = (factoryAreaId) => {
    listProductionTypeOptions.value = []
    getProductionTypeIdListInfo(factoryAreaId).then((res) => {
      res.rows.forEach(item => {
        listProductionTypeOptions.value.push({
          label: item,
          value: item
        })
      })
    })
  }

  const { queryParams, form, rules } = toRefs(data)

  const height = ref('calc(100% - 100px)')

  const column = [
    { headerName: "车间", field: "fab", headerCheckboxSelection: true, checkboxSelection: true, minWidth: 80, flex: 1 },
    { headerName: "制造区域", field: "area", minWidth: 80, flex: 1 },
    { headerName: "制造类型", field: "process", minWidth: 80, flex: 1 },
    { headerName: "部门名称", field: "dept", minWidth: 80, flex: 1 },
    { headerName: "设备id", field: "eqpId", minWidth: 100, flex: 1 },
    { headerName: "源设备id", field: "moveId", minWidth: 100, flex: 1 },
    { headerName: "主设备", field: "topEqp", minWidth: 100, flex: 1 },
    { headerName: "创建人", field: "createUser", minWidth: 80, flex: 1 },
    { headerName: "创建时间", field: "createTime", minWidth: 150, flex: 1 },
    { headerName: "更新人", field: "updateUser", minWidth: 80, flex: 1 },
    { headerName: "更新时间", field: "updateTime", minWidth: 150, flex: 1 }
  ]

  column.forEach((item) => {
    item.filter = 'agMultiColumnFilter'
  })

  const gridApi = ref()

  const selectionChanged  = (params) => {
    gridApi.value = params.api
    const selectedRows = params.api.getSelectedRows()
    single.value = selectedRows.length !== 1
    multiple.value = !selectedRows.length
  }

  /** 查询产量统计列表 */
  function getList() {
    loading.value = true
    listModule(queryParams.value).then(response => {
      moduleList.value = response.rows
      total.value = response.total
      loading.value = false
    })
  }

  // 取消按钮
  function cancel() {
    open.value = false
    reset()
  }

  // 表单重置
  function reset() {
    form.value = {
      fab: null,
      area: null,
      process: null,
      dept: null,
      mainStep: null,
      eqpId: null,
      moveId: null,
      topEqp: null,
      bySiteFlag: null,
      createUser: useUserStore().name,
      createTime: null,
      updateUser: useUserStore().name,
      updateTime: null,
      eqpIdList: [],
      factoryIdOptions: [],
      factoryAreaIdOptions: [],
      listProductionTypeOptions: []
    }
    proxy.resetForm("moduleRef")
  }

  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.pageNum = 1
    getList()
  }

  /** 重置按钮操作 */
  function resetQuery() {
    queryParams.value.area = ''
    queryParams.value.process = ''
    proxy.resetForm("queryRef")
    handleQuery()
  }

  /** 新增按钮操作 */
  function handleAdd() {
    reset()
    open.value = true
    title.value = "添加产量统计"
    isEdit.value = 'N'
  }

  /** 修改按钮操作 */
  function handleUpdate(row) {
    reset()
    const _eqpId = gridApi.value.getSelectedRows()[0].eqpId
    const _moveId = gridApi.value.getSelectedRows()[0].moveId
    getModule({
      eqpId: _eqpId,
      moveId: _moveId
    }).then(response => {
      form.value = response.data
      open.value = true
      title.value = "修改产量统计"
      isEdit.value = 'Y'
    })
  }

  /** 提交按钮 */
  function submitForm() {
    proxy.$refs["moduleRef"].validate(valid => {
      if (valid) {
        if (isEdit.value == 'Y') {
          updateModule(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功")
            open.value = false
            getList()
          })
        } else {

          getModule({
            eqpId: form.value.eqpId,
            moveId: form.value.moveId
          }).then(response => {
            var flag = response.data === undefined ? 'Y' : 'N'
            if(flag === 'Y'){
              addModule(form.value).then(response => {
                proxy.$modal.msgSuccess("新增成功")
                open.value = false
                getList()
              })
            }else{
              proxy.$modal.msgError("该设备已存在")
            }
          })
        }
      }
    })
  }

  /** 删除按钮操作 */
  function handleDelete(row) {
    const _eqpIds = []
    gridApi.value.getSelectedRows().map(item => _eqpIds.push(item.eqpId) )
    proxy.$modal.confirm('是否确认删除产量统计编号为"' + _eqpIds + '"的数据项？').then(function () {
      return delModule(_eqpIds)
    }).then(() => {
      getList()
      proxy.$modal.msgSuccess("删除成功")
    }).catch(() => { })
  }

  /** 导出按钮操作 */
  function handleExport() {
    proxy.download('funConfig/module/export', {
      ...queryParams.value
    }, `module_${new Date().getTime()}.xlsx`)
  }

  getList()
</script>
